package com.controladores.controlvehicular;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
//import android.view.View;
//import android.webkit.WebChromeClient.CustomViewCallback;
//import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	protected TextView fuenteIU;
	protected TextView fuenteIC;
	protected TextView fuenteSM;
	protected TextView fuenteER;
	private EditText texto; 
	private TextView salidaTxt;
	private TextView contador;
	private Button btnEnviar;
	Socket sk;
	DataInputStream entrada;
	
	public DataInputStream getEntrada() {
		return entrada;
	}

	public void setEntrada(DataInputStream entrada) {
		this.entrada = entrada;
	}

	DataOutputStream salida;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	String msg = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		texto = (EditText) findViewById(R.id.editText1);
		salidaTxt = (TextView) findViewById(R.id.textView1);
		contador = (TextView) findViewById(R.id.textView2);

		ImageButton botonIL = (ImageButton)findViewById(R.id.ibtn);
		
		/*try {
			String destPath = "/data/data/" + getPackageName()
					+ "/databases/";
			File f = new File(destPath);
			if (!f.exists()) {
				CopyDB(getBaseContext().getAssets().open(" "),
						new FileOutputStream(destPath));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
		//	e.printStackTrace();
	//	}
	//	public void CopyDB(InputStream inputStream, outputStream outputStream) throws IOException {
			// ---copy 1K bytes at a time---
		//	byte[] buffer = new byte[1024];
			//int length;
				//while ((length = inputStream.read(buffer)) > 0) {
				//outputStream.write(buffer, 0, length);
				//	}
			//	inputStream.close();
				//outputStream.close();
		//	}
		*/
		botonIL.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				Log.v(getClass().getCanonicalName(), "Iniciando Socket...");
				Log("Enviando... " + texto.getText().toString() + "\n");
				ejecutaClienteSocket();
				
				Intent aZona = new Intent(MainActivity.this,Zona.class);
				startActivity(aZona);
				
				
			}
		});
		fuenteIU= (TextView)findViewById(R.id.etIU);
		Typeface tipofuente = Typeface.createFromAsset(getAssets(), "gloriahallelujah.ttf");
		fuenteIU.setTypeface(tipofuente);
		
		fuenteIC= (TextView)findViewById(R.id.etIC);		
		fuenteIC.setTypeface(tipofuente);
		
		fuenteSM = (TextView)findViewById(R.id.etSMfuente);
		Typeface tipofuenteT = Typeface.createFromAsset(getAssets(),"AdventPsychosis.ttf"); 
		fuenteSM.setTypeface(tipofuenteT);
		
		fuenteER = (TextView)findViewById(R.id.etER);
		fuenteER.setTypeface(tipofuenteT);
		
		String ip = "192.168.1.12";
		int puerto = 3030;
		Log.v(this.getClass().getClass().getCanonicalName(), "Socket " + ip
				+ " " + puerto);
		try {
			sk = new Socket(ip, puerto);
			Log.v(getClass().getCanonicalName(), "Se ha iniciado conexion...");
			Log("Conexion con servidor: "+ip+" Puerto: "+puerto);
			entrada = new DataInputStream(new BufferedInputStream(
					sk.getInputStream()));
			salida = new DataOutputStream(new BufferedOutputStream(
					sk.getOutputStream()));

		} catch (UnknownHostException e) {
			e.printStackTrace();
			salidaTxt.append(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			salidaTxt.append(e.getMessage());
		}

		// ---------------------------------------------------------------
		final Handler myHandler = new Handler();

		(new Thread(new Runnable() {

			public void run() {
				while (true) {

					String recibe;
					try {
						recibe = getEntrada().readUTF();
						if (recibe != null) {
							MainActivity.this.setMsg(recibe);
							Log.v(getClass().getCanonicalName(),
									"Recibiendo datos.." + recibe);
						}

					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					myHandler.post(new Runnable() {
						public void run() {
							actualizarMensajes();
						}
					});
				}
			}
		})).start();

		// ---------------------------------------------------------------
		Log.v(getClass().getCanonicalName(),
				"Terminando de iniciar componentes");
	}

	private void ejecutaClienteSocket() {
		try {
			Log.v(getClass().getCanonicalName(), "Enviando datos..."
					+ texto.getText().toString());
			salida.writeUTF(texto.getText().toString());
			salida.flush();
		} catch (Exception e) {
			Log.v(this.getClass().getClass().getCanonicalName(), e.getMessage());
		}
		//Recibe datos de respuesta del servidor
		//try {
			//String recibe = entrada.readUTF();
			//Log("Recibiendo... " + recibe);
			//Log.v(getClass().getCanonicalName(), "Recibiendo datos.." + recibe);
		
		//} catch (IOException e) {
		  //TODO Auto-generated catch block
			//e.printStackTrace();
		 //}

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			sk.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	static int val = 0;

	protected void Log(String dato) {
		Log.v("Enviando a log valor: " + val, dato);
		salidaTxt.append(dato + "\n");
		val = val + 1;
	}

	static int cont = 0;

	private void delay(long tiempo) {
		try {
			Thread.sleep(tiempo);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void actualizaContador() {
		cont = cont + 1;
		contador.setText(Integer.toString(cont));
	}

	private void actualizarMensajes() {
		this.Log(getMsg());

	}

}
